//
//  CommitDetialViewController.swift
//  GiteeClient
//
//  Created by 王志标 on 2020/10/27.
//

import UIKit
import UITableView_FDTemplateLayoutCell
import PKHUD

/// 提交详情界面
class CommitDetialViewController: BaseViewController {

    var commitDetialTableView:UITableView!
    var detialHCellID = "commitDetialHeaderCell"
    var detialBCellID = "commitDetialBodyCell"
    
    var commitModel:CommitModel?
    var projectModel:ProjectMdoel?
    
    var diffArray:[DiffModel]?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        loadData()
    }
    

    init(project: ProjectMdoel, commitM: CommitModel) {
        super.init(nibName: nil, bundle: nil)
        self.projectModel = project
        self.commitModel = commitM
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setupUI(){
        var frame = view.bounds
        frame.size.height -= Common.topHeight
        commitDetialTableView = UITableView(frame: frame, style: .grouped)
        view.addSubview(commitDetialTableView)
        
        commitDetialTableView.delegate = self
        commitDetialTableView.dataSource = self
        commitDetialTableView.separatorStyle = .none
        
        
        commitDetialTableView.register(UINib(nibName: "CommitDetialTableViewCell", bundle: nil), forCellReuseIdentifier: detialHCellID)
        commitDetialTableView.register(UINib(nibName: "CommitBodyTableViewCell", bundle: nil), forCellReuseIdentifier: detialBCellID)
        if #available(iOS 13.0, *) {
            commitDetialTableView.backgroundColor = Colors.backgroundColor
        }
        
    }
    
    func loadData(){
        
        let url = URLs.V3URL + URLs.PROJECTS + self.projectModel!.id.description + "/repository/commits/\(self.commitModel!.id.description)/diff"
        
        // 异步加载
        DispatchQueue.global().async {
        
            let result:Result<[DiffModel?]> = NetWorkTool.shared.getArrayRequest(url: url, parameters: nil)
            
            DispatchQueue.main.async {
                if result.code == 0 {
                    self.diffArray = result.data as? [DiffModel]
                    self.commitDetialTableView.reloadData()
                }else {
                    HUD.flash(.label(result.message), delay: 2.0)
                }
            }
        }
    }
}


extension CommitDetialViewController: UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        }
        else {
            return diffArray?.count ?? 0
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: detialHCellID, for: indexPath) as! CommitDetialTableViewCell
            cell.model = self.commitModel
            return cell
            
        }else {
            
            let model = self.diffArray![indexPath.row]
            let cell = tableView.dequeueReusableCell(withIdentifier: detialBCellID, for: indexPath) as! CommitBodyTableViewCell
            cell.model = model
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return section == 0 ? 0.1 : 44
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.section == 0 {
            return tableView.fd_heightForCell(withIdentifier: detialHCellID) { (cell) in
                (cell as! CommitDetialTableViewCell).model = self.commitModel
            }
        }else {
            return tableView.fd_heightForCell(withIdentifier: detialBCellID) { (cell) in
                let model = self.diffArray![indexPath.row]
                (cell as! CommitBodyTableViewCell).model = model
            }
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 0
        {
            return nil
        }
        
        let titleLabel = UILabel()
        let count = self.diffArray?.count ?? 0
    
        if #available(iOS 13.0, *) {
            titleLabel.textColor = Colors.labelColor
        } else {
            titleLabel.textColor = Colors.BLUE_COLOR
        }
        titleLabel.font = UIFont.boldSystemFont(ofSize: 16)
        titleLabel.text = "  \(count) 个文件发生变化"
        
        return titleLabel
    }
   
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 1 {
            
            let model = self.diffArray![indexPath.row]
            if model.type == "text" {
                let vc = CommitFileViewController(model: model, commitM: self.commitModel!, nameSpace: self.projectModel!.path_with_namespace!)
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.listViewDidScrollCallback?(scrollView)
    }
}

extension CommitDetialViewController: JXPagingViewListViewDelegate {
    public func listView() -> UIView {
        return self.view
    }
    
    public func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> ()) {
        self.listViewDidScrollCallback = callback
    }

    public func listScrollView() -> UIScrollView {
        return self.commitDetialTableView
    }
}
